package api

import (
	"github.com/gin-gonic/gin"
	"go_api/config"
	"go_api/model"
	"go_api/pkg/bcrypt"
	"go_api/pkg/validator"
	"go_api/request"
	"strconv"
)

type AuthController struct {
	BaseController
}

type UserData struct {
	UId     int    `json:"u_id"`     //员工ID
	Phone   string `json:"phone"`    //手机号
	Name    string `json:"name"`     //姓名
	HeadImg string `json:"head_img"` //头像
	Token   string `json:"token"`    //当前登录token
}

// Login 用户登录
func (auth AuthController) Login(c *gin.Context) {
	//数据验证
	var data request.UserLoginRequest
	msg, ok := validator.ValidatorData(c, &data)
	if !ok {
		auth.responseError(c, 1, msg)
		return
	}
	var userData UserData
	userModel := model.XUser{}
	//根据手机号获取用户
	userInfo, err := userModel.GetUserByPhone(data.Phone)
	if err != nil {
		auth.responseError(c, 1, "查找失败")
		return
	}
	if userInfo.ID <= 0 {
		auth.responseError(c, 1, "用户不存在")
		return
	}

	//密码验证
	passCheck := bcrypt.GetPasswordUtil().Verify(userInfo.Password, data.Password)
	if !passCheck {
		auth.responseError(c, 1, "密码错误")
		return
	}
	//重置token
	var tokenStr string
	tokenStr, err = bcrypt.GetPasswordUtil().Encrypt(strconv.Itoa(userInfo.ID))
	if err != nil {
		auth.responseError(c, 1, "token生成失败")
		return
	}
	err = userModel.UpdateToken(userInfo.ID, tokenStr)
	if err != nil {
		auth.responseError(c, 1, err.Error())
		return
	}
	//返回数据
	userData.UId = userInfo.ID
	userData.Phone = userInfo.Phone
	userData.Name = userInfo.Name
	userData.HeadImg = config.GetEnv("WEB_HOST") + userInfo.HeadImg
	userData.Token = tokenStr

	auth.responseSuccess(c, userData)
}
